package org.tgcloud.group.service.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.LockUtil;
import org.tgcloud.group.core.PasswordHelper;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.core.contractUtils.PDFTest;
import org.tgcloud.group.core.session.Session;
import org.tgcloud.group.core.session.SessionFactory;
import org.tgcloud.group.entity.LogInfo;
import org.tgcloud.group.entity.MjBusinessPerson;
import org.tgcloud.group.entity.SysManagerUser;
import org.tgcloud.group.repository.LogInfoMapper;
import org.tgcloud.group.repository.MjBusinessPersonMapper;
import org.tgcloud.group.repository.SysManagerUserMapper;
import org.tgcloud.group.web.controller.req.LoginReq;

import java.util.*;

import static org.tgcloud.group.core.BaseLogger.printErrorInfo;
import static org.tgcloud.group.core.contractUtils.PDFTest.createPDF;

/**
 * @author: zhy
 * @create: 2023-07-17 11:55
 * @description:
 */
@Service
public class LoginManagerService {

    @Autowired
    private PasswordHelper passwordHelper;

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private SysManagerUserMapper managerUserMapper;

    @Autowired
    private LogInfoMapper logInfoMapper;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    public APPResultMessage doLogin(LoginReq req) {
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        String key = "doLoginManageUser_" + req.getUsername();
        String requestId = UUID.randomUUID().toString();
        boolean flag = LockUtil.tryGetDistributedLock(key, requestId);
        if (flag) {
            try {
                Integer i = doGetLoginUserType(req.getUsername());
                if (i == 1){
                    successMessage = doGetManagerUser(req);
                } else if (i == 2) {
                    successMessage = doGetBusinessUser(req);
                }
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                printErrorInfo(e);
                successMessage = APPResultMessage.SYSTEM_ERROR();
            } finally {
                LockUtil.releaseDistributedLock(key, requestId);
                return successMessage;
            }
        } else {
            return APPResultMessage.SYSTEM_BUSY();
        }
    }

    public APPResultMessage doGetManagerUser(LoginReq req){
        SysManagerUser user = managerUserMapper.selectByUsername(req.getUsername());
        if (user == null) {
            return APPResultMessage.getErrorMessage("账户不存在");
        }
        if (user.getStatus().intValue() == 2){
            return APPResultMessage.getErrorMessage("账户已被禁用");
        }
        boolean bool = passwordHelper.checkManagerPassIsCorrect(user, req.getPassword());
        if (bool) {
            APPResultMessage message = APPResultMessage.getSuccessMessage();
            return doUpLoginLogInfo(message, user, req.getDeviceId(), req.getDeviceType());
        } else {
            return APPResultMessage.getErrorMessage("用户名密码错误");
        }
    }

    public APPResultMessage doUpLoginLogInfo(APPResultMessage message, SysManagerUser user, String deviceId, Short deviceType) {
        LogInfo info = logInfoMapper.selectSuccessLoginInfo(user.getId(), (short) 1, deviceType);
        Map map = new HashMap();
        map.put("username", user.getUsername());
        map.put("userId", user.getId());
        String[] split = user.getRoleId().split(",");
        List<Integer> list = new ArrayList<>();
        for (String s : split){
            list.add(Integer.parseInt(s));
        }
        map.put("role", list);
        if (info != null) {
//            if (info.getDeviceId().equals(deviceId) && info.getDeviceType().equals(deviceType)) {
                if (sessionFactory.getSession(info.getToken()) != null) {
                    message = APPResultMessage.getSuccessMessage();
                    ResultMessage result = ResultMessage.builder();
                    result.setToken(info.getToken());
                    result.setData(map);
                    message.setResult(result);
                    return message;
                }
//            }
        }
        Session session = sessionFactory.createSession(user.getId(), deviceType, deviceId, user.getRoleId(), null, null);
        ResultMessage result = ResultMessage.builder();
        result.setToken(session.getId().toString());
        result.setData(map);
        message.setResult(result);
        managerUserMapper.updateLastTimeById(user.getId());
        logInfoMapper.insertSelective(new LogInfo(user.getId(), session.getId().toString(), deviceId, deviceType, deviceType));
        if (info != null) { // 过期token
            info.setStatus((short) 2);
            info.setUpdateTime(new Date(System.currentTimeMillis()));
            logInfoMapper.updateByPrimaryKey(info);
            sessionFactory.destroySession(info.getToken());
        }
        return message;
    }

    public APPResultMessage doGetBusinessUser(LoginReq req){
        MjBusinessPerson user = businessPersonMapper.selectCountByTelephone(req.getUsername());
        if (user == null) {
            return APPResultMessage.getErrorMessage("账户不存在");
        }
//        if (user.getStatus().intValue() == 2){
//            return APPResultMessage.getErrorMessage("账户已辞职");
//        }
        boolean bool = passwordHelper.checkBusinessPassIsCorrect(user, req.getPassword());
        if (bool) {
            APPResultMessage message = APPResultMessage.getSuccessMessage();
            return doUpLoginLogInfoByBusiness(message, user, req.getDeviceId(), (short) 3);
        } else {
            return APPResultMessage.getErrorMessage("用户名密码错误");
        }
    }

    public APPResultMessage doUpLoginLogInfoByBusiness(APPResultMessage message, MjBusinessPerson user, String deviceId, Short deviceType) {
        LogInfo info = logInfoMapper.selectSuccessLoginInfo(user.getId(), (short) 1, deviceType);
        Map map = new HashMap();
        map.put("username", user.getUsername());
        map.put("userId", user.getId());
        map.put("role", user.getRoleId());
        map.put("area", user.getAreaId());
        if (info != null) {
            if (sessionFactory.getSession(info.getToken()) != null) {
                message = APPResultMessage.getSuccessMessage();
                ResultMessage result = ResultMessage.builder();
                result.setToken(info.getToken());
                result.setData(map);
                message.setResult(result);
                return message;
            }
        }
        Session session = sessionFactory.createSession(user.getId(), deviceType, deviceId, user.getRoleId(), null, null);
        ResultMessage result = ResultMessage.builder();
        result.setToken(session.getId().toString());
        result.setData(map);
        message.setResult(result);
        managerUserMapper.updateLastTimeById(user.getId());
        logInfoMapper.insertSelective(new LogInfo(user.getId(), session.getId().toString(), deviceId, deviceType, deviceType));
        if (info != null) { // 过期token
            info.setStatus((short) 2);
            info.setUpdateTime(new Date(System.currentTimeMillis()));
            logInfoMapper.updateByPrimaryKey(info);
            sessionFactory.destroySession(info.getToken());
        }
        return message;
    }


    public Integer doGetLoginUserType(String username){
        // 1、管理员，2、商务
        Integer loginUserType = 0;
        SysManagerUser user = managerUserMapper.selectByUsername(username);
        if (user != null){
            loginUserType = 1;
        }else {
            MjBusinessPerson businessPerson = businessPersonMapper.selectCountByTelephone(username);
            loginUserType = 2;
            if (businessPerson != null && businessPerson.getStatus() == 1){
            }
        }
        return loginUserType;
    }


    public APPResultMessage doSign1() throws Exception{
        // 模版文件
        String templateFilePath = "https://mj.mejour.cn/test/20190646_1.pdf";
        // 保存PDF文件
        String pdfFilePath = "/home/html/mj/test/test1.pdf";
        // 表单数据
        HashMap<String,String> data = new HashMap<>();
        data.put("year","2023");
        data.put("month","8");
        data.put("day","14");
        data.put("name","https://mj.mejour.cn/test/sign.png");
        // 图片数据
        HashMap<String,String> imageData = new HashMap<>();
        imageData.put("sign","https://mj.mejour.cn/test/sign.png");

        // 根据PDF模版生成PDF文件
        createPDF(templateFilePath,data,imageData,true,pdfFilePath);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doUpUserPassword(int userId, short userType, String password) {
        APPResultMessage message = new APPResultMessage(6001, "修改失败，请重试");
        if (userType == 2){
            // 管理员密码修改
            SysManagerUser sysManagerUser = managerUserMapper.selectByPrimaryKey(userId);
            sysManagerUser.setPassword(password);
            passwordHelper.encryptPasswordManagerUser(sysManagerUser);
            managerUserMapper.updateByPrimaryKeySelective(sysManagerUser);
            message = APPResultMessage.getSuccessMessage();
        }else if (userType == 3){
            // 商务密码修改
            MjBusinessPerson businessPerson = businessPersonMapper.selectByPrimaryKey(userId);
            businessPerson.setPassword(password);
            passwordHelper.encryptPasswordBusinessUser(businessPerson);
            businessPersonMapper.updateByPrimaryKeySelective(businessPerson);
            message = APPResultMessage.getSuccessMessage();
        }
        return message;
    }
}
